package com.nettest.service.security;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.AntPathRequestMatcher;
import org.springframework.security.web.util.RequestMatcher;
import org.springframework.stereotype.Service;

/**
 * 实现SecurityMetadataSource接口，用于定义安全资源的相关方法
 * 
 * @author Administrator
 * 
 */
@Service("securityMetadataSource")
public class SecurityMetadataSourceImpl implements
		FilterInvocationSecurityMetadataSource {
	private RequestMatcher urlMatcher = null;
	@Autowired
	private SecutiryMetadataSourceProvider secutiryMetadataSourceProvider;
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	public Collection<ConfigAttribute> getAttributes(Object object)
			throws IllegalArgumentException {
		Map<String, Collection<ConfigAttribute>> securityMetadataSource = secutiryMetadataSourceProvider
				.getSecurityMetadataSource();
		// 获取请求的url
		HttpServletRequest request = ((FilterInvocation) object).getRequest();
		// 获取资源角色集合所有的key
		Iterator<String> iterator = securityMetadataSource.keySet().iterator();
		// 循环这些key，比较请求的url和所有的资源url，如果有相同的，则返回其对应的角色集合
		while (iterator.hasNext()) {
			String sourceUrl = iterator.next();
			urlMatcher = new AntPathRequestMatcher(sourceUrl);
			if (urlMatcher.matches(request)) {
				return securityMetadataSource.get(sourceUrl);
			}
		}
		return null;
	}

	public boolean supports(Class<?> clazz) {
		return FilterInvocation.class.isAssignableFrom(clazz);
	}

	public RequestMatcher getUrlMatcher() {
		return urlMatcher;
	}

	public void setUrlMatcher(RequestMatcher urlMatcher) {
		this.urlMatcher = urlMatcher;
	}

	public SecutiryMetadataSourceProvider getSecutiryMetadataSourceProvider() {
		return secutiryMetadataSourceProvider;
	}

	public void setSecutiryMetadataSourceProvider(
			SecutiryMetadataSourceProvider secutiryMetadataSourceProvider) {
		this.secutiryMetadataSourceProvider = secutiryMetadataSourceProvider;
	}
}
